<script setup>
import { getElementSize } from '@/views/study/three/composables'
import { useResizeObserver } from '@vueuse/core'
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { CSS2DObject, CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js'

const webgl = ref(null)

let labelRenderer = null
let renderer = null
let camera = null

onMounted(() => {
  const { width, height } = getElementSize(webgl)

  const scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(30, width / height, 0.1, 1000)

  camera.position.set(5, 5, 5)

  const lights = []
  lights[0] = new THREE.DirectionalLight('#FFF', 5)
  lights[1] = new THREE.DirectionalLight('#FFF', 5)
  lights[2] = new THREE.DirectionalLight('#FFF', 5)

  lights[0].position.set(0, 200, 0)
  lights[1].position.set(100, 200, 100)
  lights[2].position.set(-100, -200, -100)

  scene.add(...lights)

  renderer = new THREE.WebGLRenderer()
  renderer.setSize(width, height)
  webgl.value.appendChild(renderer.domElement)

  const orbit = new OrbitControls(camera, renderer.domElement)
  orbit.enableDamping = true

  labelRenderer = new CSS2DRenderer()
  labelRenderer.render(scene, camera)
  labelRenderer.setSize(width, height)
  labelRenderer.domElement.style.position = 'absolute'
  labelRenderer.domElement.style.top = '0'
  labelRenderer.domElement.style.left = '0'
  webgl.value.appendChild(labelRenderer.domElement)

  const dom = document.createElement('div')
  dom.innerHTML = 'test'

  const tag = new CSS2DObject(dom)

  scene.add(tag)

  function render() {
    requestAnimationFrame(render)

    orbit.update()

    renderer.render(scene, camera)
    labelRenderer.render(scene, camera)
  }

  render()
})

function resizeHandler() {
  const { width, height } = getElementSize(webgl)

  camera.aspect = width / height
  camera.updateProjectionMatrix()

  renderer.setSize(width, height)

  labelRenderer.setSize(width, height)
}

useResizeObserver(webgl, () => {
  resizeHandler()
})
</script>

<template>
  <div>
    <div ref="webgl" h="full" relative w="full" />
  </div>
</template>
